package ventana;

import model.LoginModel;

import org.uqbar.arena.actions.MessageSend;
import org.uqbar.arena.layout.ColumnLayout;
import org.uqbar.arena.layout.VerticalLayout;
import org.uqbar.arena.widgets.Button;
import org.uqbar.arena.widgets.Label;
import org.uqbar.arena.widgets.Panel;
import org.uqbar.arena.widgets.Selector;
import org.uqbar.arena.widgets.TextBox;
import org.uqbar.arena.windows.SimpleWindow;
import org.uqbar.arena.windows.WindowOwner;
import org.uqbar.commons.model.UserException;

public class LoginWindow extends SimpleWindow<LoginModel> {
	
	public LoginWindow(WindowOwner parent) {
		super(parent, new LoginModel());
	}
	
	@Override
	protected void addActions(Panel actionsPanel) {
		new Button(actionsPanel)
		.setCaption("Entrar")
		.onClick(new MessageSend(this, "loguear"))
		.setAsDefault();
		
		new Button(actionsPanel)
		.setCaption("Salir")
		.onClick(new MessageSend(this, "salir"));
	}

	@Override
	protected void createFormPanel(Panel mainPanel) {
		this.setTitle("Aterrizar.com - Gestión de vuelos");
		mainPanel.setLayout(new VerticalLayout());

		Panel searchFormPanel = new Panel(mainPanel);
		searchFormPanel.setLayout(new ColumnLayout(2));
		
		new Label(searchFormPanel).setText("Usuario: ");
		
		Selector<String> selectorUsuario = new Selector<String>(searchFormPanel).allowNull(false);
		selectorUsuario.bindValueToProperty("usuarioSeleccionado");
		selectorUsuario.bindItemsToProperty("usuarios");
		
		new Label(searchFormPanel).setText("Password: ");
		new TextBox(searchFormPanel).bindValueToProperty("password");
	}
	
	public void loguear() {
		if(this.getModelObject().loguear()) { 
			this.close();
			new AterrizarMainWindow(this, this.getModelObject().getUsuarioSeleccionado()).open();
		} else {
			throw new UserException("Password incorrecta");
		}
	}
	
	public void salir() {
		this.close();
	}

}